package com.xinghen.common.core.mybatis;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.xinghen.common.base.GlobalConstant;
import com.xinghen.common.base.model.dto.LoginUser;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;

/**
 * @author xinghen
 * @ClassName: BaseEntity
 * @Package: com.xinghen.common.base.model.entity
 * @Description entity基类
 * @create 2018-04-16 15:45
 */
@Data
public class BaseEntity implements Serializable {

    private static final long serialVersionUID = 2393269568666085258L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    /**
     * 版本号
     */
    private Integer version;

    /**
     * 创建人
     */
    private String creator;

    /**
     * 创建人ID
     */
    @Column(name = "creator_id")
    private Long creatorId;

    /**
     * 创建时间
     */
    @Column(name = "created_time")
    @DateTimeFormat(pattern = GlobalConstant.Time.COMMON_FORMAT_PATTERN)
    @JsonFormat(pattern = GlobalConstant.Time.COMMON_FORMAT_PATTERN, timezone = GlobalConstant.Time.DEFAULT_TIME_ZONE)
    private Date createdTime;

    /**
     * 最近操作人
     */
    @Column(name = "last_operator")
    private String lastOperator;

    /**
     * 最后操作人ID
     */
    @Column(name = "last_operator_id")
    private Long lastOperatorId;

    /**
     * 更新时间
     */
    @Column(name = "update_time")
    @DateTimeFormat(pattern = GlobalConstant.Time.COMMON_FORMAT_PATTERN)
    @JsonFormat(pattern = GlobalConstant.Time.COMMON_FORMAT_PATTERN, timezone = GlobalConstant.Time.DEFAULT_TIME_ZONE)
    private Date updateTime;

    @Transient
    private Integer pageNum;

    @Transient
    private Integer pageSize;

    @Transient
    private String orderBy;

    @Transient
    @JsonIgnore
    public boolean isNew() {
        return this.id == null;
    }

    @Transient
    @JsonIgnore
    public void setUpdateInfo(LoginUser user) {
        if (isNew()) {
            this.creatorId = (this.lastOperatorId = user.getUserId());
            this.creator = user.getUsername();
            this.createdTime = (this.updateTime = new Date());
        }
        this.lastOperatorId = user.getUserId();
        this.lastOperator = user.getUsername() == null ? user.getLoginName() : user.getUsername();
        this.updateTime = new Date();
    }
}
